package com.ygqh.baby.service.task.impl;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.ao.TaskMethod;
import com.ygqh.baby.handler.BiOrderStatisticsHandler;
import com.ygqh.baby.handler.OffShopBiOrderHandler;
import com.ygqh.baby.kids.service.KidsOrderService;
import com.ygqh.baby.model.PreSaleRemind;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.task.YgBiTaskService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author admin
 */
@Service
public class YgBiTaskServiceImpl implements YgBiTaskService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private YgUserOpenService ygUserOpenService;
    @Autowired
    private YgChannelService ygChannelService;
    @Autowired
    private YgTaskTimeService ygTaskTimeService;
    @Autowired
    private BiOrderDayService biOrderDayService;
    @Autowired
    private BiChannelDayService biChannelDayService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private AdminContractDetailService adminContractDetailService;
    @Autowired
    private WdtQybOrderService wdtQybOrderService;
    @Autowired
    private BiSkuSaleService biSkuSaleService;
    @Autowired
    private BiSupplierOrderDayService biSupplierOrderDayService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private YgSkuMaterialService ygSkuMaterialService;
    @Autowired
    private AdminSkuService adminSkuService;
    @Autowired
    private KidsOrderService kidsOrderService;
    @Autowired
    private BiOrderStatisticsHandler biOrderStatisticsHandler;
    @Autowired
    private OffShopBiOrderHandler offShopBiOrderHandler;

    @Value("${mail.to.yushou}")
    private String yushou;

    @Override
    public void channelScan(int limitTime) {
        logger.debug("【channelScan】：开始执行渠道统计的定时任务... ");
        Date currentTime = new Date();
        long diffMinutes = 0;
        Date startDate = new Date();
        Date endDate = new Date();
        // 执行次数
        long count = 0;
        try {
            YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.ChannelScan);
            if (taskTime != null) {
                // 获取最后一次执行时间与当前时间的间隔
                diffMinutes = DateConvertUtils.diffMinutes(taskTime.getRunTime(), currentTime);
                count = diffMinutes / limitTime;
                System.out.println("【ChannelScan】：currentTime = " + DateConvertUtils.formatDateTime(currentTime)
                        + ";lastRunTime = " + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差"
                        + diffMinutes + "分钟，该任务执行间隔为" + limitTime + "分钟的数据，即此次需执行" + count + "次");
            }
            if (count > 0) {
                startDate = taskTime.getRunTime();
                endDate = DateConvertUtils.addMinute(taskTime.getRunTime(), Integer.parseInt(count + "") * limitTime);
                // logger.debug("【ChannelScan】：开始执行第" + (i + 1) +
                // "次，startDate  =" +
                // DateConvertUtils.formatDateTime(startDate));

                ygChannelService.executeChannelScanAndRegTask(startDate, endDate);
                ygTaskTimeService.updateTaskTime(taskTime.getId(), TaskMethod.ChannelScan, endDate,
                        ";currentTime = " + DateConvertUtils.formatDateTime(currentTime) + "lastRunTime = "
                                + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差【"
                                + diffMinutes + "】分钟，该任务执行间隔为【" + limitTime + "】分钟的数据，即此次需执行【" + count + "】次");

            }
            logger.debug("【ChannelScan】：执行渠道统计的定时任务结束... ");
            System.out.println("【ChannelScan】：执行渠道统计的定时任务结束... ");
        } catch (Exception e) {
            logger.error("【ChannelScan】：执行渠道统计的定时任务失败... ", e);
            e.printStackTrace();
        }

    }

    public void channelScan1(int limitTime) {
        logger.debug("【ChannelScan】：开始执行渠道统计的定时任务... ");
        Date currentTime = new Date();
        long diffMinutes = 0;
        Date startDate = new Date();
        Date endDate = new Date();
        // 执行次数
        long count = 0;
        try {
            YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.ChannelScan);
            List<YgChannel> channelList = new ArrayList<YgChannel>();
            if (taskTime != null) {
                // 获取最后一次执行时间与当前时间的间隔
                diffMinutes = DateConvertUtils.diffMinutes(taskTime.getRunTime(), currentTime);
                count = diffMinutes / limitTime;
                System.out.println("【ChannelScan】：currentTime = " + DateConvertUtils.formatDateTime(currentTime)
                        + ";lastRunTime = " + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差"
                        + diffMinutes + "分钟，该任务执行间隔为" + limitTime + "分钟的数据，即此次需执行" + count + "次");
            }

            for (int i = 0; i < count; i++) {

                startDate = DateConvertUtils.addMinute(taskTime.getRunTime(), i * limitTime);
                endDate = DateConvertUtils.addMinute(startDate, limitTime);
                logger.debug("【ChannelScan】：开始执行第" + (i + 1) + "次，startDate  ="
                        + DateConvertUtils.formatDateTime(startDate));
                List<YgUserOpen> openUserList = ygChannelService.findChannelScanAmount(startDate, endDate);
                List<YgUser> userList = ygChannelService.findChannelRegAmount(startDate, endDate);

                // List<YgChannel> scanList =
                // this.getChannelScanList(openUserList);
                List<YgChannel> scanList = new ArrayList<YgChannel>();

                // ==获取扫码集合
                // 根据不同主渠道进行分组
                Map<String, List<YgUserOpen>> mainDetailMap = new LinkedHashMap<String, List<YgUserOpen>>();
                List<String> mainChannelCodes = new ArrayList<String>();

                for (YgUserOpen userOpen : openUserList) {
                    if (StringUtil.isNotBlank(userOpen.getFromCode())) {
                        YgChannel mainChannel = ygChannelService.findByCode(userOpen.getFromCode());
                        if (mainChannel != null) {
                            if (mainChannel.getParentId().intValue() != 0) {
                                mainChannel = ygChannelService.findById(mainChannel.getParentId());
                            }
                            List<YgUserOpen> mainDetails = mainDetailMap.get(mainChannel.getSourceCode());
                            if (mainDetails == null) {
                                mainDetails = new ArrayList<YgUserOpen>();
                                mainDetailMap.put(mainChannel.getSourceCode(), mainDetails);
                                mainChannelCodes.add(mainChannel.getSourceCode());
                            }
                            mainDetails.add(userOpen);
                        }
                    }
                }

                if (mainChannelCodes.size() > 0) {
                    for (String mainChannelCode : mainChannelCodes) {
                        List<YgUserOpen> userOpenList = mainDetailMap.get(mainChannelCode);

                        YgChannel mainChannel = new YgChannel();
                        mainChannel.setSourceCode(mainChannelCode);
                        mainChannel.setScanAmount((long) userOpenList.size());
                        mainChannel.setRegAmount(0l);
                        scanList.add(mainChannel);

                    }
                }
                // ====
                // 获取新增用户集合
                // List<YgChannel> regList = this.getChannelRegList(userList);
                List<YgChannel> regList = new ArrayList<YgChannel>();

                // 根据不同主渠道进行分组
                Map<String, List<YgUser>> mainRegDetailMap = new LinkedHashMap<String, List<YgUser>>();
                List<String> mainRegChannelCodes = new ArrayList<String>();

                for (YgUser user : userList) {
                    if (StringUtil.isNotBlank(user.getFromCode())) {
                        YgChannel mainChannel = ygChannelService.findByCode(user.getFromCode());

                        if (mainChannel != null) {
                            if (mainChannel.getParentId().intValue() != 0) {
                                mainChannel = ygChannelService.findById(mainChannel.getParentId());
                            }
                            List<YgUser> mainDetails = mainRegDetailMap.get(mainChannel.getSourceCode());
                            if (mainDetails == null) {
                                mainDetails = new ArrayList<YgUser>();
                                mainRegDetailMap.put(mainChannel.getSourceCode(), mainDetails);
                                mainRegChannelCodes.add(mainChannel.getSourceCode());
                            }
                            mainDetails.add(user);
                        }
                    }
                }

                if (mainRegChannelCodes.size() > 0) {
                    for (String mainChannelCode : mainRegChannelCodes) {
                        List<YgUser> uList = mainRegDetailMap.get(mainChannelCode);

                        YgChannel mainChannel = new YgChannel();
                        mainChannel.setSourceCode(mainChannelCode);
                        mainChannel.setRegAmount((long) uList.size());
                        mainChannel.setScanAmount(0l);
                        regList.add(mainChannel);
                    }
                }

                // ======================================================

                logger.debug("【ChannelScan】：开始执行第" + (i + 1) + "次，scanList  =" + scanList.toString());
                logger.debug("【ChannelScan】：开始执行第" + (i + 1) + "次，regList  =" + regList.toString());
                channelList.addAll(scanList);
                channelList.addAll(regList);
            }

            if (channelList.size() > 0) {
                // 更新数据
                ygChannelService.updateScanAmountBatch(channelList);
            }
            if (count > 0) {
                ygTaskTimeService.updateTaskTime(taskTime.getId(), TaskMethod.ChannelScan, endDate,
                        ";currentTime = " + DateConvertUtils.formatDateTime(currentTime) + "lastRunTime = "
                                + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差【"
                                + diffMinutes + "】分钟，该任务执行间隔为【" + limitTime + "】分钟的数据，即此次需执行【" + count + "】次");

            }
            logger.debug("【ChannelScan】：执行渠道统计的定时任务结束... ");
            System.out.println("【ChannelScan】：执行渠道统计的定时任务结束... ");
        } catch (Exception e) {
            logger.error("【ChannelScan】：执行渠道统计的定时任务失败... ", e);
            e.printStackTrace();
        }

    }

    private List<YgChannel> getChannelScanList(List<YgUserOpen> openUserList) {

        List<YgChannel> channelList = new ArrayList<YgChannel>();
        // 根据不同主渠道进行分组
        Map<String, List<YgUserOpen>> mainDetailMap = new LinkedHashMap<String, List<YgUserOpen>>();
        List<String> mainChannelCodes = new ArrayList<String>();

        for (YgUserOpen userOpen : openUserList) {
            if (StringUtil.isNotBlank(userOpen.getFromCode())) {
                YgChannel mainChannel = ygChannelService.findByCode(userOpen.getFromCode());
                if (mainChannel != null) {
                    if (mainChannel.getParentId().intValue() != 0) {
                        mainChannel = ygChannelService.findById(mainChannel.getParentId());
                    }
                    List<YgUserOpen> mainDetails = mainDetailMap.get(mainChannel.getSourceCode());
                    if (mainDetails == null) {
                        mainDetails = new ArrayList<YgUserOpen>();
                        mainDetailMap.put(mainChannel.getSourceCode(), mainDetails);
                        mainChannelCodes.add(mainChannel.getSourceCode());
                    }
                    mainDetails.add(userOpen);
                }
            }
        }

        if (mainChannelCodes.size() > 0) {
            for (String mainChannelCode : mainChannelCodes) {
                List<YgUserOpen> userOpenList = mainDetailMap.get(mainChannelCode);

                YgChannel mainChannel = new YgChannel();
                mainChannel.setSourceCode(mainChannelCode);
                mainChannel.setScanAmount((long) userOpenList.size());
                mainChannel.setRegAmount(0l);
                channelList.add(mainChannel);

                // 根据不同子渠道进行分组
                Map<String, List<YgUserOpen>> subDetailMap = new LinkedHashMap<String, List<YgUserOpen>>();
                List<String> subChannelCodes = new ArrayList<String>();
                for (YgUserOpen userOpen : userOpenList) {
                    if (!mainChannelCode.equals(userOpen.getFromCode())) {
                        List<YgUserOpen> subDetails = subDetailMap.get(userOpen.getFromCode());
                        if (subDetails == null) {
                            subDetails = new ArrayList<YgUserOpen>();
                            subDetailMap.put(userOpen.getFromCode(), subDetails);
                            subChannelCodes.add(userOpen.getFromCode());
                        }
                        subDetails.add(userOpen);
                    }
                }

                if (subChannelCodes.size() > 0) {
                    for (String subCode : subChannelCodes) {
                        List<YgUserOpen> subList = subDetailMap.get(subCode);
                        YgChannel subChannel = new YgChannel();
                        subChannel.setSourceCode(subCode);
                        subChannel.setScanAmount((long) subList.size());
                        subChannel.setRegAmount(0l);
                        channelList.add(subChannel);
                    }
                }

            }
        }
        return channelList;
    }

    private List<YgChannel> getChannelRegList(List<YgUser> userList) {

        List<YgChannel> channelList = new ArrayList<YgChannel>();
        // 根据不同主渠道进行分组
        Map<String, List<YgUser>> mainDetailMap = new LinkedHashMap<String, List<YgUser>>();
        List<String> mainChannelCodes = new ArrayList<String>();

        for (YgUser user : userList) {
            if (StringUtil.isNotBlank(user.getFromCode())) {
                YgChannel mainChannel = ygChannelService.findByCode(user.getFromCode());

                if (mainChannel != null) {
                    if (mainChannel.getParentId().intValue() != 0) {
                        mainChannel = ygChannelService.findById(mainChannel.getParentId());
                    }
                    List<YgUser> mainDetails = mainDetailMap.get(mainChannel.getSourceCode());
                    if (mainDetails == null) {
                        mainDetails = new ArrayList<YgUser>();
                        mainDetailMap.put(mainChannel.getSourceCode(), mainDetails);
                        mainChannelCodes.add(mainChannel.getSourceCode());
                    }
                    mainDetails.add(user);
                }
            }
        }

        if (mainChannelCodes.size() > 0) {
            for (String mainChannelCode : mainChannelCodes) {
                List<YgUser> uList = mainDetailMap.get(mainChannelCode);

                YgChannel mainChannel = new YgChannel();
                mainChannel.setSourceCode(mainChannelCode);
                mainChannel.setRegAmount((long) uList.size());
                mainChannel.setScanAmount(0l);
                channelList.add(mainChannel);

                // 根据不同子渠道进行分组
                Map<String, List<YgUser>> subDetailMap = new LinkedHashMap<String, List<YgUser>>();
                List<String> subChannelCodes = new ArrayList<String>();
                for (YgUser user : uList) {
                    if (!mainChannelCode.equals(user.getFromCode())) {
                        List<YgUser> subDetails = subDetailMap.get(user.getFromCode());
                        if (subDetails == null) {
                            subDetails = new ArrayList<YgUser>();
                            subDetailMap.put(user.getFromCode(), subDetails);
                            subChannelCodes.add(user.getFromCode());
                        }
                        subDetails.add(user);
                    }
                }

                if (subChannelCodes.size() > 0) {
                    for (String subCode : subChannelCodes) {
                        List<YgUser> subUList = subDetailMap.get(subCode);
                        YgChannel subChannel = new YgChannel();
                        subChannel.setSourceCode(subCode);
                        subChannel.setRegAmount((long) subUList.size());
                        subChannel.setScanAmount(0l);
                        channelList.add(subChannel);
                    }
                }

            }
        }
        return channelList;
    }

    @Override
    public void statisticsOrderByDay() {
        logger.debug("【statisticsOrderByDay】：开始执行每日订单统计的定时任务... ");
        System.out.println("【statisticsOrderByDay】：开始执行每日订单统计的定时任务... ");
        Date currentTime = new Date();
        long diffDate = 0;
        Date startDate = new Date();
        Date endDate = new Date();
        // 执行次数
        long count = 0;
        try {
            YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.StatisticsOrderByDay);
            if (taskTime != null) {
                // 获取最后一次执行时间与当前时间的间隔
                diffDate = DateConvertUtils.diffDayes(taskTime.getRunTime(), currentTime);
                count = diffDate / 1;
                System.out.println("【StatisticsOrderByDay】：currentTime = "
                        + DateConvertUtils.formatDateTime(currentTime) + ";lastRunTime = "
                        + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差" + diffDate
                        + "天，该任务执行间隔为" + 1 + "天的数据，即此次需执行" + count + "次");
            }
            List<BiOrderDay> orderDayList = new ArrayList<BiOrderDay>();
            for (int i = 0; i < count; i++) {
                startDate = DateConvertUtils.addDay(taskTime.getRunTime(), i);
                endDate = DateConvertUtils.addDay(startDate, 1);
                System.out.println("开始执行第" + (i + 1) + "次，startDate=" + DateConvertUtils.formatDateTime(startDate)
                        + ",endDate=" + DateConvertUtils.formatDateTime(endDate));

                BiOrderDay biOrderDay = this.executeOrderStatistics(startDate, endDate);
                if (biOrderDay != null) {
                    orderDayList.add(biOrderDay);
                }

                System.out.println("执行第" + (i + 1) + "次结束，startDate=" + startDate + ",endDate=" + endDate);
            }
            if (orderDayList.size() > 0) {
                biOrderDayService.addBiOrderDayBatch(orderDayList);
            }
            if (count > 0) {
                ygTaskTimeService.updateTaskTime(taskTime.getId(), TaskMethod.StatisticsOrderByDay, endDate,
                        ";currentTime = " + DateConvertUtils.formatDateTime(currentTime) + "lastRunTime = "
                                + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差【" + diffDate
                                + "】天，该任务执行间隔为【1】天的数据，即此次需执行【" + count + "】次");

            }
            logger.debug("【StatisticsOrderByDay】： 执行每日订单统计的定时任务结束... ");
            System.out.println("【StatisticsOrderByDay】： 执行每日订单统计的定时任务结束... ");
        } catch (Exception e) {
            System.out.println("【StatisticsOrderByDay】： 执行每日订单统计的定时任务失败... ");
            e.printStackTrace();
        }
    }

    @Override
    public void statisticsOrderNew(String... shopNo) {
        biOrderStatisticsHandler.statisticsOrder(shopNo);
    }

    /**
     * 订单日报不考虑支付后取消的订单，支付订单数据为当天支付的订单（可能包含昨天创建的订单）
     *
     * @param startDate
     * @param endDate   入参
     * @return BiOrderDay 返回类型
     * @throws
     * @Title: executeOrderStatistics
     * @author （guohao）
     * @date 2017年11月28日 上午10:45:44
     * @version V1.0
     */
    private BiOrderDay executeOrderStatistics(Date startDate, Date endDate) {
        List<BiOrderDay> list = biOrderDayService.executeOrderStatistics(startDate, endDate);
        BiOrderDay biOrderDay = null;
        if (!CollectionUtils.isEmpty(list)) {
            biOrderDay = list.get(0);
            biOrderDay.setOrderDate(startDate);
            biOrderDay.setCreateTime(new Date());
            biOrderDay.setShopType("yiigoo");
            biOrderDay.setShopName("yiigooshop");
        }
        if (biOrderDay != null) {
            BiOrderDay grossProfit = this.executeOrderDateGrossProfit(startDate, endDate);
            if (grossProfit != null) {
                biOrderDay.setTotalCostPrice(grossProfit.getTotalCostPrice());
                biOrderDay.setGrossMargin(grossProfit.getGrossMargin());
            } else {
                biOrderDay.setTotalCostPrice(new BigDecimal(0));
                biOrderDay.setGrossMargin(new BigDecimal(0));
            }
        }
        return biOrderDay;
    }

    /**
     * 执行订单统计
     *
     * @param startDate   每日零时
     * @param endDate     次日零时
     * @param sourceCodes
     * @return
     */
    private BiOrderDay executeOrderStatistics(Date startDate, Date endDate, String[] sourceCodes) {
        BiOrderDay orderDay = new BiOrderDay();
        Long totalOrderCount = 0l; // 总订单数
        BigDecimal totalOrderPrice = new BigDecimal(0);// 总订单金额
        Long payOrderCount = 0l;// 总支付订单数
        BigDecimal payOrderPrice = new BigDecimal(0);// 总支付订单金额
        List<Long> payUserIdList = new ArrayList<Long>();
        List<Long> userIdList = new ArrayList<Long>();

        List<String> payOrderStatus = new ArrayList<String>();
        payOrderStatus.add(OrderStatus.WaitingSend.name());
        payOrderStatus.add(OrderStatus.WaitingSign.name());
        payOrderStatus.add(OrderStatus.TradeSuccess.name());

        List<YgOrder> orderList = biOrderDayService.findOrderByDay(startDate, endDate, sourceCodes);
        for (YgOrder order : orderList) {
            totalOrderCount++;
            totalOrderPrice = totalOrderPrice.add(order.getTotalPrice());
            // 已支付的订单
            if (payOrderStatus.contains(order.getOrderStatus().name())) {
                payOrderCount++;
                payOrderPrice = payOrderPrice.add(order.getTotalPrice());
                // 总支付订单人数
                if (!payUserIdList.contains(order.getUserId())) {
                    payUserIdList.add(order.getUserId());
                }

            }
            // 总下单人数
            if (!userIdList.contains(order.getUserId())) {
                userIdList.add(order.getUserId());
            }
        }
        orderDay.setTotalOrderCount(totalOrderCount);
        orderDay.setTotalOrderPrice(totalOrderPrice);
        orderDay.setPayOrderCount(payOrderCount);
        orderDay.setPayOrderPrice(payOrderPrice);
        orderDay.setPayUserCount((long) payUserIdList.size());
        orderDay.setTotalUserCount((long) userIdList.size());
        orderDay.setCreateTime(new Date());
        orderDay.setShopType("yiigoo");
        orderDay.setShopName("yiigooshop");
        orderDay.setOrderDate(startDate);
        return orderDay;
    }

    /**
     * 统计订单毛利
     *
     * @param startDate 每日零时
     * @param endDate   次日零时
     * @return
     */
    @Override
    public BiOrderDay executeOrderDateGrossProfit(Date startDate, Date endDate) {
        BiOrderDay biOrderDay = biOrderDayService.executeOrderDateGrossProfit(startDate, endDate);
        return biOrderDay;
    }

    private List<BiChannelDay> getChannelOrderList(List<YgOrder> orderList, Date orderDate) {

        List<BiChannelDay> channelDayList = new ArrayList<BiChannelDay>();
        // 根据不同主渠道进行分组
        Map<String, List<YgOrder>> mainDetailMap = new LinkedHashMap<String, List<YgOrder>>();
        List<String> mainChannelCodes = new ArrayList<String>();

        for (YgOrder order : orderList) {
            if (StringUtil.isNotBlank(order.getSourceCode())) {
                YgChannel mainChannel = ygChannelService.findByCode(order.getSourceCode());
                if (mainChannel != null) {
                    if (mainChannel.getParentId().intValue() != 0) {
                        mainChannel = ygChannelService.findById(mainChannel.getParentId());
                    }
                    List<YgOrder> mainDetails = mainDetailMap.get(mainChannel.getSourceCode());
                    if (mainDetails == null) {
                        mainDetails = new ArrayList<YgOrder>();
                        mainDetailMap.put(mainChannel.getSourceCode(), mainDetails);
                        mainChannelCodes.add(mainChannel.getSourceCode());
                    }
                    mainDetails.add(order);
                }
            }
        }
        // 每个渠道下的所有订单
        if (mainChannelCodes.size() > 0) {
            for (String channelCode : mainChannelCodes) {
                List<YgOrder> list = mainDetailMap.get(channelCode);
                YgChannel mainChannel = ygChannelService.findByCode(channelCode);
                BiChannelDay biChannelDay = new BiChannelDay();
                biChannelDay.setOrderDate(orderDate);
                biChannelDay.setChannelName(mainChannel.getChannelName());
                biChannelDay.setChannelSourceCode(channelCode);

                Long totalOrderCount = 0l; // 总订单数
                BigDecimal totalOrderPrice = new BigDecimal(0);// 总订单金额
                Long payOrderCount = 0l;// 总支付订单数
                BigDecimal payOrderPrice = new BigDecimal(0);// 总支付订单金额
                List<Long> payUserIdList = new ArrayList<Long>();
                List<Long> userIdList = new ArrayList<Long>();

                List<String> payOrderStatus = new ArrayList<String>();
                payOrderStatus.add(OrderStatus.WaitingSend.name());
                payOrderStatus.add(OrderStatus.WaitingSign.name());
                payOrderStatus.add(OrderStatus.TradeSuccess.name());

                for (YgOrder order : list) {
                    totalOrderCount++;
                    totalOrderPrice = totalOrderPrice.add(order.getTotalPrice());
                    // 已支付的订单
                    if (payOrderStatus.contains(order.getOrderStatus().name())) {
                        payOrderCount++;
                        payOrderPrice = payOrderPrice.add(order.getTotalPrice());
                        // 总支付订单人数
                        if (!payUserIdList.contains(order.getUserId())) {
                            payUserIdList.add(order.getUserId());
                        }

                    }
                    // 总下单人数
                    if (!userIdList.contains(order.getUserId())) {
                        userIdList.add(order.getUserId());
                    }
                }
                biChannelDay.setTotalOrderCount(totalOrderCount);
                biChannelDay.setTotalOrderPrice(totalOrderPrice);
                biChannelDay.setTotalUserCount((long) userIdList.size());
                biChannelDay.setPayOrderCount(payOrderCount);
                biChannelDay.setPayOrderPrice(payOrderPrice);
                biChannelDay.setPayUserCount((long) payUserIdList.size());
                channelDayList.add(biChannelDay);

            }
        }

        return channelDayList;
    }

    @Override
    public void statisticsChannelByDay() {
        logger.debug("【StatisticsOrderByDay】：开始执行每日渠道统计的定时任务... ");
        System.out.println("【StatisticsOrderByDay】：开始执行每日渠道统计的定时任务... ");
        Date currentTime = new Date();
        long diffDate = 0;
        Date startDate = new Date();
        Date endDate = new Date();
        // 执行次数
        long count = 0;
        YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.StatisticsChannelByDay);
        try {
            if (taskTime != null) {
                // 获取最后一次执行时间与当前时间的间隔
                diffDate = DateConvertUtils.diffDayes(taskTime.getRunTime(), currentTime);
                count = diffDate / 1;
                System.out.println("【statisticsChannelByDay】：currentTime = "
                        + DateConvertUtils.formatDateTime(currentTime) + ";lastRunTime = "
                        + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差" + diffDate
                        + "天，该任务执行间隔为" + 1 + "天的数据，即此次需执行" + count + "次");
            }
            List<BiChannelDay> biChannelDayList = new ArrayList<BiChannelDay>();
            for (int i = 0; i < count; i++) {
                startDate = DateConvertUtils.addDay(taskTime.getRunTime(), i);
                endDate = DateConvertUtils.addDay(startDate, 1);
                System.out.println("【statisticsChannelByDay】开始执行第" + (i + 1) + "次;startDate:"
                        + DateConvertUtils.formatDateTime(startDate) + ";endDate:"
                        + DateConvertUtils.formatDateTime(endDate));

                List<YgOrder> orderList = biOrderDayService.findOrderByDay(startDate, endDate, null);
                List<YgUserOpen> userOpenList = ygChannelService.findChannelScanAmount(startDate, endDate);
                List<YgUser> userList = ygChannelService.findChannelRegAmount(startDate, endDate);
                List<YgChannel> allParentChannel = ygChannelService.findAllParentChannel();

                List<BiChannelDay> channelOrderList = this.getChannelOrderList(orderList, startDate);
                List<YgChannel> channelScanList = this.getChannelScanList(userOpenList);
                List<YgChannel> regList = this.getChannelRegList(userList);

                for (YgChannel channel : allParentChannel) {
                    BiChannelDay channelDay = new BiChannelDay();
                    channelDay.setChannelName(channel.getChannelName());
                    channelDay.setChannelSourceCode(channel.getSourceCode());
                    channelDay.setOrderDate(startDate);
                    channelDay.setCreateTime(new Date());
                    channelDay.setTotalOrderCount(0L);
                    channelDay.setTotalOrderPrice(new BigDecimal(0));
                    channelDay.setTotalUserCount(0L);
                    channelDay.setPayOrderCount(0L);
                    channelDay.setPayOrderPrice(new BigDecimal(0));
                    channelDay.setPayUserCount(0L);
                    channelDay.setRegAmount(0L);
                    channelDay.setScanAmount(0L);
                    for (YgChannel regChannel : regList) {
                        if (channel.getSourceCode().equals(regChannel.getSourceCode())) {
                            channelDay.setRegAmount(regChannel.getRegAmount());
                        }
                    }
                    for (YgChannel scanChannel : channelScanList) {
                        if (channel.getSourceCode().equals(scanChannel.getSourceCode())) {
                            channelDay.setScanAmount(scanChannel.getScanAmount());
                        }
                    }
                    for (BiChannelDay order : channelOrderList) {
                        if (channel.getSourceCode().equals(order.getChannelSourceCode())) {
                            channelDay.setTotalOrderCount(order.getTotalOrderCount());
                            channelDay.setTotalOrderPrice(order.getTotalOrderPrice());
                            channelDay.setTotalUserCount(order.getTotalUserCount());
                            channelDay.setPayOrderCount(order.getPayOrderCount());
                            channelDay.setPayOrderPrice(order.getPayOrderPrice());
                            channelDay.setPayUserCount(order.getPayUserCount());
                        }
                    }
                    biChannelDayList.add(channelDay);
                }
                System.out.println("【statisticsChannelByDay】执行第" + (i + 1) + "次结束");
            }
            if (biChannelDayList.size() > 0) {
                biChannelDayService.addBiChannelDayBatch(biChannelDayList);
            }

            if (count > 0) {
                ygTaskTimeService.updateTaskTime(taskTime.getId(), TaskMethod.StatisticsChannelByDay, endDate,
                        ";currentTime = " + DateConvertUtils.formatDateTime(currentTime) + "lastRunTime = "
                                + DateConvertUtils.formatDateTime(taskTime.getRunTime()) + ";与最后一次任务执行时间相差【" + diffDate
                                + "】天，该任务执行间隔为【1】天的数据，即此次需执行【" + count + "】次");

            }

            System.out.println("【statisticsChannelByDay】：执行结束");
        } catch (Exception e) {
            logger.error("【StatisticsOrderByDay】：执行每日渠道统计的定时任务...失败 ");
            e.printStackTrace();
        }
    }

    @Override
    public BiOrderDay statisticsOrderByTime(Date startDate, Date endDate) {
        return this.executeOrderStatistics(startDate, endDate);
    }

    @Override
    public BiOrderDay statisticsByTimeForM(Date startDate, Date endDate, String[] sourceCodes) {
        BiOrderDay orderStatistics = this.executeOrderStatistics(startDate, endDate, sourceCodes);
        int scanCount = ygUserOpenService.countScanCountByFromCode(sourceCodes, startDate, endDate, null);
        int newCount = ygUserService.findNewCountByFromCode(sourceCodes, startDate, endDate);
        orderStatistics.setScanUserCount((long) scanCount);
        orderStatistics.setNewUserCount((long) newCount);
        return orderStatistics;
    }

    @Override
    public void sendPreSaleForRemind() {
        Date currentDate = new Date();
        List<PreSaleRemind> remind = adminContractDetailService.findPreSaleForRemind();
        if (!CollectionUtils.isEmpty(remind)) {

            List<String> skuList = remind.stream().map(PreSaleRemind::getSkuCode).collect(Collectors.toList());
            List<PreSaleRemind> saleCountList = wdtQybOrderService.findSaleCountBySku(skuList);

            for (PreSaleRemind preSale : remind) {
                for (PreSaleRemind sale : saleCountList) {
                    if (preSale.getSkuCode().equals(sale.getSkuCode())) {
                        preSale.setSaleAmount(sale.getSaleAmount());
                    }
                }
            }

            this.sendPreSaleMall(remind, yushou);
        }
        ygTaskTimeService.saveOrUpdate(TaskMethod.SendPreSaleForRemind.name(), currentDate, "");
    }

    ;

    private void sendPreSaleMall(List<PreSaleRemind> list, String to) {

        StringBuffer str = new StringBuffer();
        str.append("<html><head><style>.table-d table{ background:#000;font-size:14px} .table-d table td{ background:#FFF} h5{width: auto;margin-right: 20px} .title{display: flex;line-height: 10px}");
        str.append("</style></head><body>");
        str.append("<div class='table-d'>");
        str.append("<table width='1200' border='0' cellspacing='1' cellpadding='0'><tr><td width='12%'>供应商名称</td><td width='10%'>合同编号</td>"
                + "<td width='10%'>产品名称</td><td width='8%'>颜色</td><td width='10%'>sku编码</td><td width='10%'>尺码</td>"
                + "<td width='10%'>采购数量</td><td width='10%'>已售数量</td><td width='10%'>预计到货日期</td><td width='10%'>预售日期（M站）</td></tr>");
        for (PreSaleRemind detail : list) {
            str.append("<tr><td>" + detail.getSupplierName() + "</td>");
            str.append("<td>" + detail.getContractCode() + "</td>");
            str.append("<td>" + detail.getProductName() + "</td>");
            str.append("<td>" + detail.getColor() + "</td>");
            str.append("<td>" + detail.getSkuCode() + "</td>");
            str.append("<td>" + detail.getSizeName() + "</td>");
            str.append("<td>" + detail.getQuantity() + "</td>");
            str.append("<td>" + (detail.getSaleAmount() == null ? 0 : detail.getSaleAmount()) + "</td>");
            str.append("<td>" + DateConvertUtils.format(detail.getArrivedDate()) + "</td>");
            str.append("<td>" + DateConvertUtils.format(detail.getPreSaleDate()) + "</td>");
            str.append("</tr>");
        }
        str.append("</table>");
        try {
            System.out.println(str.toString());
            mailUtil.sendWithHtml(to.split(","), "每日预售通知（" + DateConvertUtils.format(new Date()) + "）", str.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void statisticalSkuSaleCount() {
        logger.info("statisticalSkuSaleCount-->开始执行 ");
        try {
            YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.StatisticalSkuSaleCount);
            logger.info("statisticalSkuSaleCount -->\r\n{}", taskTime);

            Long startId = Long.parseLong(taskTime.getRemark());
            List<WdtQybOrderDetail> detailList = wdtQybOrderService.findDetailListAfterId(startId);

            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(detailList)) {
                taskTime.setRemark(detailList.get(detailList.size() - 1).getId().toString());

                Map<String, List<WdtQybOrderDetail>> sMap = detailList.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getShopNo));

                List<BiSkuSale> newList = new ArrayList<>();
                List<BiSkuSale> oldList = new ArrayList<>();

                for (String shopNo : sMap.keySet()) {
                    List<WdtQybOrderDetail> details = sMap.get(shopNo);
                    Map<Date, List<WdtQybOrderDetail>> dateMap = details.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getCreateDate));
                    for (Map.Entry<Date, List<WdtQybOrderDetail>> entry : dateMap.entrySet()) {
                        List<WdtQybOrderDetail> value = entry.getValue();
                        doStatisticsWdtSkuHotSale(value, newList, oldList);
                    }
                }
                biSkuSaleService.addBatch(newList);
                biSkuSaleService.additionAmountBatch(oldList);
                logger.info("statisticalSkuSaleCount --> newList:\r\n{}", newList);
                logger.info("statisticalSkuSaleCount --> oldList:\r\n{}", oldList);
            }
            taskTime.setRunTime(new Date());
            ygTaskTimeService.saveOrUpdate(taskTime);
            logger.info("statisticalSkuSaleCount 执行完成-->\r\n {}", taskTime);
        } catch (Exception e) {
            logger.error("statisticalSkuSaleCount 执行失败-->\r\n {}", ExceptionUtil.getExceptionMsg(e));
        }

    }

    private void doStatisticsWdtSkuHotSale(List<WdtQybOrderDetail> detailList, List<BiSkuSale> newList, List<BiSkuSale> oldList) {
        Map<String, List<WdtQybOrderDetail>> listMap = detailList.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getSpecNo));

        List<BiSkuSale> list = new ArrayList<>();

        for (Map.Entry<String, List<WdtQybOrderDetail>> entry : listMap.entrySet()) {

            List<WdtQybOrderDetail> value = entry.getValue();
            BigDecimal count = value.stream().map(WdtQybOrderDetail::getNum).reduce(BigDecimal.ZERO, BigDecimal::add);
            String skuCode = entry.getKey();
            Date createDate = value.get(0).getCreateDate();
            String shopNo = value.get(0).getShopNo();
            String shopName = value.get(0).getShopName();
            String goodsName = value.get(0).getGoodsName();
            BiSkuSale skuSale = new BiSkuSale();
            skuSale.setSkuCode(skuCode);
            skuSale.setProductName(goodsName);
            skuSale.setShopNo(shopNo);
            skuSale.setShopName(shopName);
            skuSale.setAmount(count.longValue());
            skuSale.setBiDate(createDate);
            list.add(skuSale);
        }

        List<String> skuCodeList = new ArrayList<>(listMap.keySet());

        List<AdminSku> adminSkuList = adminSkuService.findListBySkuCode(skuCodeList);
        Map<String, List<AdminSku>> adminSkuMap = adminSkuList.stream().collect(Collectors.groupingBy(AdminSku::getSkuCode));
        for (BiSkuSale skuSale : list) {
            if (adminSkuMap.containsKey(skuSale.getSkuCode())) {
                List<AdminSku> adminSkus = adminSkuMap.get(skuSale.getSkuCode());
                skuSale.setAdminProductName(adminSkus.get(0).getProductName());
                skuSale.setShortName(adminSkus.get(0).getColor());
                skuSale.setSize(adminSkus.get(0).getSizeName());
                skuSale.setProductCode(adminSkus.get(0).getProductCode());
            } else {
                skuSale.setAdminProductName("unknown");
                skuSale.setShopName("unknown");
                skuSale.setSize("unknown");
                skuSale.setProductCode("unknown");
            }
            Boolean existed = biSkuSaleService.existed(skuSale.getShopNo(), skuSale.getSkuCode(), skuSale.getBiDate());
            if (existed) {
                oldList.add(skuSale);
            } else {
                newList.add(skuSale);
            }
        }
    }

    @Deprecated
    private void statisticalSkuSaleCountOld() {

        ygTaskTimeService.execute(TaskMethod.StatisticalSkuSaleCount, TaskMethod.StatisticalSkuSaleCount.getCode(),
                new YgTaskTimeTemplate() {

                    @Override
                    public void execute(Date runtime) {
                        String remark = "ok";
                        try {
                            Date startDate = DateConvertUtils.getDateStart(DateConvertUtils.addMinute(runtime, -60));
                            Date endDate = DateConvertUtils.addDay(startDate, 1);

                            System.err.println(DateConvertUtils.formatDateTime(startDate));
                            System.err.println(DateConvertUtils.formatDateTime(endDate));
                            System.err.println(DateConvertUtils.formatDateTime(runtime));
                            List<BiSkuSale> exitList = new ArrayList<BiSkuSale>();
                            List<BiSkuSale> list = biSkuSaleService.statisticalSkuSaleCount(null, startDate, endDate,
                                    null, null);
                            List<BiSkuSale> hasList = biSkuSaleService.findSkuSaleList(startDate, null);
                            Iterator<BiSkuSale> it = list.iterator();
                            while (it.hasNext()) {
                                BiSkuSale next = it.next();
                                if (!CollectionUtils.isEmpty(hasList)) {
                                    long count = hasList
                                            .stream()
                                            .filter(s -> s.getSkuCode().equals(next.getSkuCode())
                                                    && s.getShopNo().equals(next.getShopNo())).count();
                                    System.out.println(count);
                                    if (count > 0) {
                                        exitList.add(next);
                                        it.remove();
                                    }
                                }
                            }
                            biSkuSaleService.addBatch(list);
                            biSkuSaleService.updateAmountBatch(exitList);
                            System.out.println(list.toString());
                        } catch (Exception e) {
                            runtime = null;
                            remark = ExceptionUtil.getExceptionMsg(e);
                            ygTaskTimeService.saveOrUpdate(TaskMethod.StatisticalSkuSaleCount.name(), runtime, remark);
                            e.printStackTrace();
                            throw e;
                        }

                        // ygTaskTimeService.saveOrUpdate(TaskMethod.StatisticalSkuSaleCount.name(),
                        // runtime, remark);
                    }
                });

    }

    @Override
    public void statisticsSupplierOrderByDay() {
        TaskMethod taskMethod = TaskMethod.StatisticsSupplierOrder;
        ygTaskTimeService.execute(taskMethod, taskMethod.getCode(), new YgTaskTimeTemplate() {
            @Override
            public void execute(Date currentDate) {
                logger.info("【StatisticsOrderByDay】：" + DateConvertUtils.format(currentDate) + "开始执行品牌订单毛利统计定时任务... ");
                Date endDate = DateConvertUtils.getDateStart(currentDate);
                Date startDate = DateConvertUtils.getDateStart(DateConvertUtils.addDay(currentDate, -1));
                List<BiSupplierOrderDay> orderStatistics = biSupplierOrderDayService.
                        statisticsSupplierOrderByDay(startDate, endDate, false, true);
                if (CollectionUtils.isEmpty(orderStatistics)) {
                    logger.warn("【statisticsSupplierOrderByDay】：" + DateConvertUtils.format(startDate) + "品牌订单统计结果为空");
                    return;
                }
                logger.info("【statisticsSupplierOrderByDay】：startDate={}, endDate={}, size=" + orderStatistics.size(),
                        DateConvertUtils.formatDateTime(startDate), DateConvertUtils.formatDateTime(endDate));
                int row = biSupplierOrderDayService.saveBatch(orderStatistics);
                logger.info("【statisticsSupplierOrderByDay】：startDate={}, endDate={}, row=" + row,
                        DateConvertUtils.formatDateTime(startDate), DateConvertUtils.formatDateTime(endDate));
                if (row == 0) {
                    logger.warn("【statisticsSupplierOrderByDay】：" + DateConvertUtils.format(startDate) + "品牌订单统计结果保存异常");
                }
                logger.info("【StatisticsOrderByDay】：" + DateConvertUtils.format(currentDate) + "品牌订单毛利统计定时任务执行结束... ");
            }
        });
    }

    @Override
    public void statisticsSupplierOrderByHistory(Date startDate, Date endDate) {
        Date tempDate = DateUtils.addDays(startDate, 1);
        while (!tempDate.after(endDate)) {
            List<BiSupplierOrderDay> orderStatistics = biSupplierOrderDayService.
                    statisticsSupplierOrderByDay(startDate, tempDate, false, true);
            if (CollectionUtils.isEmpty(orderStatistics)) {
                logger.warn("【statisticsSupplierOrderByHistory】：" + DateConvertUtils.format(startDate) + "品牌订单统计结果为空");
                return;
            }
            logger.info("【statisticsSupplierOrderByHistory】：startDate={}, endDate={}, size=" + orderStatistics.size(),
                    DateConvertUtils.formatDateTime(startDate), DateConvertUtils.formatDateTime(tempDate));
            biSupplierOrderDayService.saveBatch(orderStatistics);

            startDate = tempDate;
            tempDate = DateUtils.addDays(startDate, 1);
        }
    }

    @Override
    public void statisticsSupplierOrderByDayFromKids() {
        TaskMethod taskMethod = TaskMethod.StatisticsSupplierOrderFromKids;
        ygTaskTimeService.execute(taskMethod, taskMethod.getCode(), new YgTaskTimeTemplate() {
            @Override
            public void execute(Date currentDate) throws Exception {
                logger.info("【statisticsSupplierOrderByDayFromKids】：{}开始执行线下店品牌订单毛利统计定时任务... ", DateConvertUtils.format(currentDate));
                Date endDate = DateConvertUtils.getDateStart(currentDate);
                Date startDate = DateConvertUtils.getDateStart(DateConvertUtils.addDay(currentDate, -1));
                List<BiSupplierOrderDay> orderStatistics = offShopBiOrderHandler.statisticsSupplierOrderByDate(startDate, endDate);
//                List<BiSupplierOrderDay> orderStatistics = kidsOrderService.statisticsSupplierOrderByDayFromKids(startDate, endDate);
                if (CollectionUtils.isEmpty(orderStatistics)) {
                    logger.info("【statisticsSupplierOrderByDayFromKids】：{} -> {} 未拉取到线下店商家统计数据",
                            DateConvertUtils.format(startDate), DateConvertUtils.format(endDate));
                } else {
                    biSupplierOrderDayService.saveBatch(orderStatistics);
                }
                logger.info("【statisticsSupplierOrderByDayFromKids】：{}新世界品牌订单毛利统计定时任务执行结束。", DateConvertUtils.format(currentDate));
            }

        });
    }

    @Override
    public void statisticsWdtOrder() {
        logger.info("statisticsWdtOrder-->开始执行");
        try {
            YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(TaskMethod.StatisticsWdtOrder);
            Long startId = Long.parseLong(taskTime.getRemark());
            logger.info("statisticsWdtOrder-->\r\n{}" + taskTime);
            List<WdtQybOrderDetail> detailList = wdtQybOrderService.findDetailListAfterId(startId, "002");

            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(detailList)) {
                taskTime.setRemark(detailList.get(detailList.size() - 1).getId().toString());

                Map<String, List<BiOrderDay>> map = buildBiOrderDayMap(detailList);
                List<BiOrderDay> newList = map.get("newList");
                List<BiOrderDay> oldList = map.get("oldList");
                biOrderDayService.addBiOrderDayBatch(newList);
                biOrderDayService.additionBatch(oldList);
            }

            taskTime.setRunTime(new Date());
            ygTaskTimeService.saveOrUpdate(taskTime);
            logger.info("statisticsWdtOrder 执行完成 -->\r\n{}", taskTime);
        } catch (Exception e) {
            logger.info("statisticsWdtOrder-->执行失败 \r\n {}", ExceptionUtil.getExceptionMsg(e));

        }

    }

    @Override
    public Map<String, List<BiOrderDay>> buildBiOrderDayMap(List<WdtQybOrderDetail> detailList) {

        Map<String, List<BiOrderDay>> map = new HashMap<>();

        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(detailList)) {

            List<BiOrderDay> newList = new ArrayList<>();
            List<BiOrderDay> oldList = new ArrayList<>();

            List<String> skuCodeList = detailList.stream().map(WdtQybOrderDetail::getSpecNo).distinct().collect(Collectors.toList());

            System.out.println(JSON.toJSONString(skuCodeList));
            List<YgSkuMaterial> skuList = ygSkuMaterialService.findListBySkuCode(skuCodeList);

            List<AdminSku> adminSkuList = adminSkuService.findListBySkuCode(skuCodeList);
            Map<String, List<YgSkuMaterial>> listMap = skuList.stream().collect(Collectors.groupingBy(YgSkuMaterial::getSkuCode));
            Map<String, List<AdminSku>> adminSkuMap = adminSkuList.stream().collect(Collectors.groupingBy(AdminSku::getSkuCode));
            for (WdtQybOrderDetail orderDetail : detailList) {
                if (listMap.containsKey(orderDetail.getSpecNo())) {
                    List<YgSkuMaterial> skuMaterials = listMap.get(orderDetail.getSpecNo());
                    orderDetail.setCostPrice(skuMaterials.get(0).getCostPrice());
                }
                if (adminSkuMap.containsKey(orderDetail.getSpecNo())) {
                    List<AdminSku> skuMaterials = adminSkuMap.get(orderDetail.getSpecNo());
                    orderDetail.setWarehouseNo(skuMaterials.get(0).getWarehouseNo());
                } else {
                    orderDetail.setWarehouseNo("009");
                }
            }

            Map<String, List<WdtQybOrderDetail>> sMap = detailList.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getShopNo));

            for (String shopNo : sMap.keySet()) {
                List<WdtQybOrderDetail> details = sMap.get(shopNo);
                Map<Date, List<WdtQybOrderDetail>> dateMap = details.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getCreateDate));
                for (Map.Entry<Date, List<WdtQybOrderDetail>> entry : dateMap.entrySet()) {
                    List<WdtQybOrderDetail> shopList = entry.getValue();

                    doStatisticsWdtOrder(shopList, newList, oldList, "0");
                    Map<String, List<WdtQybOrderDetail>> warehouseMap = shopList.stream().collect(Collectors.groupingBy(WdtQybOrderDetail::getWarehouseNo));

                    for (Map.Entry<String, List<WdtQybOrderDetail>> warehouseEntry : warehouseMap.entrySet()) {
                        doStatisticsWdtOrder(warehouseEntry.getValue(), newList, oldList, warehouseEntry.getKey());
                    }

                }
            }
            logger.info("statisticsWdtOrder --> newList:\r\n{}", newList);
            logger.info("statisticsWdtOrder --> oldList:\r\n{}", oldList);

            map.put("newList", newList);
            map.put("oldList", oldList);
        }
        return map;
    }

    @Override
    public void statisticsOrderFromKids() {
        TaskMethod taskMethod = TaskMethod.StatisticsOrderFromKids;
        ygTaskTimeService.execute(taskMethod, taskMethod.getCode(), new YgTaskTimeTemplate() {
            @Override
            public void execute(Date currentTime) throws Exception {
                logger.info("【statisticsOrderByDayFromKids】：{}开始执行线下店订单合计统计定时任务... ", DateConvertUtils.formatDateTime(currentTime));
                Date endTime = DateConvertUtils.addMinute(currentTime, -2);
                Date startTime = DateConvertUtils.addMinute(endTime, -taskMethod.getCode());
                offShopBiOrderHandler.statisticsOrderByTime(startTime, endTime);
                logger.info("【statisticsOrderByDayFromKids】：{}线下店订单合计统计定时任务执行结束。", DateConvertUtils.formatDateTime(currentTime));
            }

        });
    }

    private void doStatisticsWdtOrder(List<WdtQybOrderDetail> detailList, List<BiOrderDay> newList, List<BiOrderDay> oldList, String warehouseNo) {
        BigDecimal totalPrice = detailList.stream().map(WdtQybOrderDetail::getPaid).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalCostPrice = detailList.stream().map(WdtQybOrderDetail::getTotalCostPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        long orderCount = detailList.stream().map(WdtQybOrderDetail::getSrcTid).distinct().count();
        BiOrderDay orderDay = new BiOrderDay();
        Date createDate = detailList.get(0).getCreateDate();
        String shopNo = detailList.get(0).getShopNo();
        String shopName = detailList.get(0).getShopName();
        orderDay.setOrderDate(createDate);
        orderDay.setTotalOrderPrice(totalPrice);
        orderDay.setTotalOrderCount(orderCount);
        orderDay.setPayOrderCount(orderCount);
        orderDay.setPayOrderPrice(totalPrice);
        orderDay.setTotalCostPrice(totalCostPrice);
        orderDay.setNewUserCount(0L);
        orderDay.setPayUserCount(0L);
        orderDay.setTotalUserCount(0L);
        orderDay.setWarehouseNo(warehouseNo);
        BigDecimal grossMargin = BigDecimal.ZERO;
        if (totalPrice.compareTo(BigDecimal.ZERO) > 0) {
            grossMargin = orderDay.getPayOrderPrice().subtract(orderDay.getTotalCostPrice())
                    .divide(orderDay.getPayOrderPrice(), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        }
        orderDay.setGrossMargin(grossMargin);
        orderDay.setShopType(shopNo);
        orderDay.setShopName(shopName);
        BiOrderDay byShop = biOrderDayService.findByShop(shopNo, createDate, warehouseNo);
        orderDay.setUpdateTime(new Date());
        if (byShop == null) {
            orderDay.setCreateTime(new Date());
            newList.add(orderDay);
        } else {
            oldList.add(orderDay);
        }
    }

}